package com.newway.wechat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.newway.common.MyPages;
import com.newway.common.Result;
import com.newway.util.QRCodeUtil;
import com.newway.wechat.context.UserInfo;
import com.newway.wechat.context.UserInfoContext;
import com.newway.wechat.entity.OrgEntity;
import com.newway.wechat.entity.OrgUserEntity;
import com.newway.wechat.enums.BusinessTypeEnum;
import com.newway.wechat.mapper.OrgMapper;
import com.newway.wechat.mapper.OrgUserMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/wechat")
public class OrgController {

    @Autowired
    Environment environment;

    @Resource
    OrgMapper orgMapper;

    @Resource
    OrgUserMapper orgUserMapper;

    @GetMapping("/org/list")
    public Result getOrgList(OrgEntity requestDto){
        requestDto.getParams().put("pageNum",(requestDto.getPageNum()-1)* requestDto.getPageSize());
        MyPages<OrgEntity> selectPage = new MyPages<>();
        requestDto.setCreator(UserInfoContext.getUserInfo().getId());
        long totals =  orgMapper.getOrgListCount(requestDto);
        if(totals>0){
            List<OrgEntity> result =  orgMapper.getOrgList(requestDto);
            selectPage.setTotal(totals);
            selectPage.setPages(totals%requestDto.getPageSize()==0?totals/requestDto.getPageSize():(totals/requestDto.getPageSize())+1);
            selectPage.setRecords(result);
        }
      return Result.success(selectPage);
    }

    /**
     * 根据id查找
     * @param id
     * @return
     */
    @GetMapping("/org/getById")
    public Result getOrgById(@PathVariable("id") Long id){
        OrgEntity orgEntity = orgMapper.selectById(id);
        if(orgEntity==null){
            return Result.fail("数据不存在");
        }
        return Result.success(orgEntity);
    }

    /**
     * 创建
     * @param orgEntity
     * @return
     */
    @PostMapping("/org/Add")
    public Result orgAdd(@RequestParam("file") MultipartFile file, HttpServletRequest request, @ModelAttribute OrgEntity orgEntity){
        String UPLOAD_DIR = environment.getProperty("img.uploadPath");
        String mappingPath = environment.getProperty("img.mappingPath");
        UserInfo userInfo = UserInfoContext.getUserInfo();
        QueryWrapper<OrgEntity> orgEntityQueryWrapper = new QueryWrapper<>();
        orgEntityQueryWrapper.eq("creator", userInfo.getId());
        List<OrgEntity> orgEntities = orgMapper.selectList(orgEntityQueryWrapper);
        if(orgEntities.size()>=5){
            return Result.fail("已超过五个，不可再创建了");
        }
        try {
            // 1. 验证文件
            if (file.isEmpty()) {
                return Result.fail("请选择文件");
            }
            // 2. 限制文件大小 (10MB)
            long maxSize = 2 * 1024 * 1024;
            if (file.getSize() > maxSize) {
                return Result.fail("文件大小不能超过2MB");
            }
            // 3. 验证文件类型
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (!Arrays.asList(".jpg", ".jpeg", ".png", ".gif", ".pdf").contains(fileExtension.toLowerCase())) {
                return Result.fail("不支持的文件类型");
            }
            // 4. 创建存储目录
            File uploadPath = new File(UPLOAD_DIR);
            if (!uploadPath.exists()) {
                uploadPath.mkdirs();
            }
            // 5. 生成唯一文件名
            String fileName = UUID.randomUUID() + fileExtension;
            // 6. 保存文件
            File dest = new File(uploadPath.getAbsolutePath() + File.separator + fileName);
            file.transferTo(dest);

            // 7. 返回访问URL
//            String fileUrl = request.getScheme() + "://" + request.getServerName() + ":" +
//                    request.getServerPort() + "/" + UPLOAD_DIR + fileName;

            orgEntity.setCreator(userInfo.getId());
            orgEntity.setAvatar(mappingPath+fileName);
            orgMapper.insert(orgEntity);
            OrgUserEntity orgUserEntity = new OrgUserEntity(null,userInfo.getId(),orgEntity.getId());
            orgUserMapper.insert(orgUserEntity);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("上传失败: " + e.getMessage());
        }
    }

    /**
     * 删除（解散）
     * @param id
     * @return
     */
    @PostMapping("/org/delete/{id}")
    public Result orgDelete(@PathVariable("id") Long id){
        UserInfo userInfo = UserInfoContext.getUserInfo();
        OrgEntity orgEntity = orgMapper.selectById(id);
        if(orgEntity ==null){
            return Result.fail("请刷新重试");
        }
        if(!orgEntity.getCreator().equals(userInfo.getId())){
            return Result.fail("无操作权限");
        }
        orgMapper.deleteById(id);
        UpdateWrapper<OrgUserEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("org_id",id);
        orgUserMapper.delete(updateWrapper);
        return Result.success();
    }

    /**
     * 加入
     * @param id
     * @return
     */
    @PostMapping("/org/join/{id}")
    public Result orgJoin(@PathVariable("id") Long id){
        UserInfo userInfo = UserInfoContext.getUserInfo();
        OrgEntity orgEntity = orgMapper.selectById(id);
        if(orgEntity ==null){
            return Result.fail("当前数据不存在，请确认");
        }
        QueryWrapper<OrgUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userInfo.getId());
        queryWrapper.eq("org_id",id);
        OrgUserEntity orgUserEntity = orgUserMapper.selectOne(queryWrapper);
        if(orgUserEntity!=null){
            return Result.fail("不可重复加入");
        }
        orgUserEntity = new OrgUserEntity(null, userInfo.getId(), id);
        orgUserMapper.insert(orgUserEntity);
        return Result.success();
    }

    @GetMapping("/org/jsonQr/{id}")
    public Result jsonQr(@PathVariable("id") Long id) throws Exception {
        OrgEntity orgEntity = orgMapper.selectById(id);
        if(orgEntity == null){
            return Result.fail("无效的二维码");
        }
        // 1. 组装业务 JSON
        Map<String, Object> json = new HashMap<>();
        json.put("id", id);
        json.put("avatar", orgEntity.getAvatar());
        json.put("orgName", orgEntity.getOrgName());
        json.put("toPath","/pages/org/join/join?id="+id);
        json.put("businessType", BusinessTypeEnum.JOIN_IN.code);
        String content = new ObjectMapper().writeValueAsString(json);
        String base64 = QRCodeUtil.generateQRCodeBase64(content);
        return Result.success(base64);
    }
}
